"use strict";

const { Controller } = require("egg");
const { successRes, failRes } = require("../extend/helper");
const fs = require("fs");
const path = require("path");
const sendToWormhole = require("stream-wormhole");
const uuid = require("uuid");
const { Journal } = require("../exception/Journal");

function getDate() {
  var nowDate = new Date();
  var year = nowDate.getFullYear();
  var month =
    nowDate.getMonth() + 1 < 10
      ? "0" + (nowDate.getMonth() + 1)
      : nowDate.getMonth() + 1;
  var day =
    nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
  var dateStr = `${year}-${month}-${day}`;
  return dateStr;
}

/**
 * 判读路径是否存在,如不存在创建文件夹
 * @param pathStr 参数要用path.join()拼接,项目下的相对路径
 * @return projectPath 返回绝对路径,可要可不要
 */
function mkdirPath(pathStr) {
  var projectPath = path.join(process.cwd());
  var tempDirArray = pathStr.split("\\");

  for (var i = 0; i < tempDirArray.length; i++) {
    projectPath = projectPath + "/" + tempDirArray[i];
    if (fs.existsSync(projectPath)) {
      var tempstats = fs.statSync(projectPath);
      if (!tempstats.isDirectory()) {
        fs.unlinkSync(projectPath);
        fs.mkdirSync(projectPath);
      }
    } else {
      fs.mkdirSync(projectPath);
    }
  }
  return projectPath;
}

class cUploadFile extends Controller {
  async upload() {
    const { ctx } = this;
    // let url = '', fileType = 1, remarks = '', response = null;
    // const stream = await ctx.getFileStream();
    // try {
    //   // 获取文件备注
    //   remarks = stream?.fields?.remarks ?? '';
    //   // 获取本地文件夹路径
    //   const bashPath = path.join("app/public/upload", getDate());
    //   mkdirPath(bashPath); // 生成本地对应文件夹
    //   // 获取文件名
    //   const filename = getDate() + '/' + uuid.v1() + path.extname(stream.filename).toLocaleLowerCase();
    //   // 获取本地文件路径
    //   const localFilePath = path.join(__dirname, "../public/upload", filename);
    //   // 创建本地文件写入流
    //   const writeStream = fs.createWriteStream(localFilePath);
    //   // 将文件写入本地
    //   await new Promise((resolve, reject) => {
    //     stream.pipe(writeStream)
    //       .on('error', reject)
    //       .on('finish', resolve);
    //   });
    //   // 判断文件类型
    //   if (stream?.filename && stream.filename.indexOf('.pdf') > -1) {
    //     fileType = 1;
    //   }
    //   if (stream?.filename && stream.filename.indexOf('.mp4') > -1) {
    //     fileType = 2;
    //   }
    //   if (stream?.filename && (stream.filename.indexOf('.jpg') > -1 || stream.filename.indexOf('.png') > -1)) {
    //     fileType = 3;
    //   }
    //   // 获取文件url
    //   url = 'public/upload/' + filename;
    //   // 获取参数
    //   const params = {
    //     classificate: fileType,
    //     name: stream?.filename ?? '',
    //     url: url,
    //     remarks: remarks
    //   }
    //   // await ctx.model.Resource.create(params, { attributes: ['id', 'classificate', 'name', 'url', 'remarks'] });
    //   await Journal(ctx, { params, operatorType: '文件资源 -> 上传', code: 200 });
    //   response = successRes(params);
    // } catch (error) {
    //   console.log('error: ', error);
    //   await sendToWormhole(stream);
    //   await Journal(ctx, { operatorType: '文件资源 -> 上传', code: 401 });
    //   url = '';
    //   response = failRes(401);
    // }
    const url = await ctx.service.uploadFile.uploadFiles();
    ctx.body = successRes(url);
  }

  async uploadAvatar () {
    console.log('uploadAvatar');
    const { ctx } = this;
    const result = await ctx.service.sUploadAvatar.uploadFiles();
    ctx.body = successRes(result);
  }
}

module.exports = cUploadFile;
